package main

import (
	"context"
	"fmt"
	"net/http"
	"os"

	openai "github.com/sashabaranov/go-openai"
)

var client = openai.NewClient("your token")

// demo2 封装了聊天接口
func main() {
	http.HandleFunc("/chat", chat)

	err := http.ListenAndServe(":3002", nil)
	if err != nil {
		_, _ = fmt.Fprint(os.Stderr, "ListenAndServe: "+err.Error())
		return
	}
}

func chat(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	content := r.Form.Get("content")
	if len(content) == 0 {
		fmt.Fprintln(w, "参数错误")
		return
	}
	fmt.Fprintln(w, handleChat(content))
}

func handleChat(content string) string {
	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: openai.GPT3Dot5Turbo,
			Messages: []openai.ChatCompletionMessage{
				{
					Role:    openai.ChatMessageRoleUser,
					Content: "Hello!",
				},
			},
		},
	)

	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
		return ""
	}

	fmt.Printf("请求：%s\n响应：%s\n", content, resp.Choices[0].Message.Content)
	return resp.Choices[0].Message.Content
}
